package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.hosp.repository.ScheduleRepository;
import com.atguigu.yygh.hosp.service.ScheduleService;
import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.vo.hosp.ScheduleQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service
public class SchedulServiceImpl implements ScheduleService {

    @Autowired
    ScheduleRepository repository;

    /**
     * 上传排班接口
     *
     * @param paramMap
     */
    @Override
    public void save(Map<String, Object> paramMap) {
        //paramMap 转为对象
        String s = JSONObject.toJSONString(paramMap);
        Schedule schedule = JSONObject.parseObject(s, Schedule.class);


        // 根据医院和排版序号
        Schedule tem =
                repository.getScheduleByHoscodeAndHosScheduleId(schedule.getHoscode(), schedule.getHosScheduleId());
        if (tem != null) {
            tem.setUpdateTime(new Date());
            tem.setIsDeleted(0);
            tem.setStatus(1);
            repository.save(tem);
        } else {
            schedule.setCreateTime(new Date());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(0);
            schedule.setStatus(1);
            repository.save(schedule);
        }
    }

    @Override
    public Page<Schedule> findPageSchedule(int page, int limit, ScheduleQueryVo vo) {
        Pageable pageable = PageRequest.of(page - 1, limit);

        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        Schedule deps = new Schedule();
        BeanUtils.copyProperties(vo, deps);
        deps.setIsDeleted(0);
        deps.setStatus(1);
        Example<Schedule> dep = Example.of(deps, matcher);
        Page<Schedule> all = repository.findAll(dep, pageable);
        return all;
    }

    @Override
    public void remove(String hoscode, String hosScheduleId) {
        Schedule tem = repository.getScheduleByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        if (tem != null) {
            repository.deleteById(tem.getId());
        }
    }
}
